﻿namespace Trader.Analyzing
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using BO.Interface;
    using DataServices.Interface;
    using Indicators.Interface;
    using Interface;

    public class StockSignalSimulator : IStockSignalSimulator
    {
        private readonly ISignal signal;
        private readonly ISignalsCache signalsCache;
        private readonly IStock stock;

        public StockSignalSimulator(IStock stock, ISignal signal, ISignalsCache signalsCache)
        {
            this.stock = stock;
            this.signal = signal;
            this.signalsCache = signalsCache;
        }

        #region IStockSignalSimulator Members

        ///<summary>
        ///Simulate
        ///</summary>
        ///<param name="tradingDate"></param>
        ///<returns></returns>
        public IActionPoints Simulate(DateTime tradingDate)
        {
            DateTime? lastCheckedDate = signalsCache.FindLastCachedDate(stock, signal.ID);

            if (lastCheckedDate == null)
            {
                IEnumerable<DateTime> calculatedDates = from quote in stock.Quotes
                                                        where
                                                            quote.Key < tradingDate &&
                                                            signal.GenerateRecommendation(stock, quote.Key) ==
                                                            Recommendation.BUY
                                                        select quote.Key;
                signalsCache.CacheSignalSimulationResults(stock, signal.ID, tradingDate - TimeSpan.FromDays(1),
                                                          calculatedDates);
            }
            else if (lastCheckedDate < tradingDate - TimeSpan.FromDays(1))
            {
                IEnumerable<DateTime> calculatedDates = from quote in stock.Quotes
                                                        where
                                                            quote.Key < tradingDate && quote.Key > lastCheckedDate.Value &&
                                                            signal.GenerateRecommendation(stock, quote.Key) ==
                                                            Recommendation.BUY
                                                        select quote.Key;
                signalsCache.CacheSignalSimulationResults(stock, signal.ID, tradingDate - TimeSpan.FromDays(1),
                                                          calculatedDates);
            }

            var buyPoints = new ActionPoints();
            buyPoints.AddRange(signalsCache.LoadToDate(stock, signal.ID, tradingDate - TimeSpan.FromDays(1)));

            return buyPoints;
        }

        #endregion
    }
}